/**
 * Created by chocolate on 16/5/18.
 */

//引入系统模块
import React, {
  Component,
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableOpacity,
  TabBarIOS,
  ListView,
  Image,
} from 'react-native';

var Title =require('./Title');
var query = require('./Query').query;
var SearchBar = require('react-native-search-bar');
var dismissKeyboard = require('dismissKeyboard');
class ChatList extends Component{

  //props,外部调用NoticeList的时候,传入的属性
  constructor(props){
    super(props);
    this.parent = this.props.parent;

    this.ds = new ListView.DataSource({
      getRowData:(dataBlob,sectionID,rowID)=>{
        return dataBlob[sectionID][rowID];
      },
      getSectionHeaderData:(dataBlob,sectionID)=>{
        return dataBlob[sectionID];
      },
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged:(s1,s2) => s1 !== s2
    });

    this.addressList = [];
    this.state = {
        showsCancelButton:false,
        searchText:'',
        dataSource:this.ds.cloneWithRows(this.addressList),
      }
  }

  componentDidMount(){
    this._refreshAddresslist();
  }

  _refreshAddresslist(){
    //this.setState({isLoading:true});
    this.addressList = [];
    query.getLatestContactor(this.parent.phone,this,function(owner,response){
      if(response.success === true){
        owner.addressList = response.message;
        owner._updateLiswView(owner.addressList);}})
  }

  _updateLiswView(addressList){
    let sectionIDs = Object.keys(addressList);
    let rowIDs = sectionIDs.map(sectionID => {
      let count = addressList[sectionID].length;
      let thisRow = [];
      for(let i = 0; i < count; i++){
        thisRow.push(i);
      }
      return thisRow;
    });
    this.setState({dataSource:this.ds.cloneWithRowsAndSections(addressList,sectionIDs,rowIDs)});
  }

  _onPressRow(sectionID,rowData){
    console.log("_onPressRow");
    if(sectionID === "contactor"){
      this.props.navigator.push({name:'ChatScreen',params:{group:false,myside:this.parent.phone,yourside:rowData.phone,yourPicture:rowData.imgUrl}});
    }
    else{
      this.props.navigator.push({name:'ChatScreen',params:{group:true,myside:this.parent.phone,yourside:rowData.id}});
    }
  }

  _onSearchButtonPress(){
    if(this.state.searchText !== '')
    {
      let tmpAddressList = {};
      let sectionIDs = Object.keys(this.addressList);
      let rowIDs = sectionIDs.map(sectionID => {
        tmpAddressList[sectionID] = [];
        let count = this.addressList[sectionID].length;
        for(let i = 0; i < count; i++){
          var array = this.addressList[sectionID];
          var string = array[i].name;
          if(string.search(this.state.searchText) != -1)
          {
            tmpAddressList[sectionID].push(this.addressList[sectionID][i]);
          }
        }
      })
      this._updateLiswView(tmpAddressList);
    }
    console.log("pressed search button");
  }

  _onCancelButtonPress(){
    this.setState({showsCancelButton: false});
    this._updateLiswView(this.addressList);
  }

  _onChangeText(value){
    this.setState({searchText:value});
  }
    

  _renderSeparator(sectionID, rowID, adjacentRowHighlighted){
    return(
      <View style={styles.separatorView} key={"sectionID_"+sectionID+"_rowID_"+rowID}> 
      </View>
    )
  }

  _renderSectionHeader(sectionData,sectionID){
    let type = sectionID === 'group' ? '群组' : '消息';
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.setionHeaderText}>
          {type}
        </Text>
      </View>
    );
  }

  _renderRecord(rowData: any,sectionID: any, rowID: any){

    if(sectionID === 'group'){
      return (
        <TouchableOpacity onPress = {()=>{this._onPressRow(sectionID,rowData);}}>
          <View style={styles.listRow}>
            <View style={[styles.avatar,{backgroundColor:'#eee',alignItems:'center',justifyContent:'center'}]}>
              <Text style={{fontSize:10,color:'#aaa'}}>{rowData.school.slice(-4)}</Text>
            </View>
            <Text style={styles.contactor}>{rowData.name}</Text>
            <View style={styles.location}>
              <Text style={styles.school}>{rowData.school}</Text>
              <View style={{width:10}}/>
              <Text style={styles.school}>{rowData.banji}</Text>
            </View>
          </View>
        </TouchableOpacity>
      )
    }
    else{
      return (
        <TouchableOpacity onPress = {()=>{this._onPressRow(sectionID,rowData);}}>
          <View style={styles.listRow}>
            <Image style={styles.avatar} source={{uri:rowData.imgUrl,isStatic: true}}/>
            <Text style={styles.contactor}>{rowData.name}</Text>
            <View style={styles.location}>
              <View style={{width:10}}/>
              <Text style={styles.school}>{rowData.latestMsg}</Text>
              <Text style={[styles.school,{marginLeft:80}]}>{rowData.date}</Text>
            </View>
          </View>
        </TouchableOpacity>
      )
    }
  }


  //渲染学校公告列表(应该以日期作为section header,每条内容为:标题、摘要、学校)
  render(){
    return(
      <View style={styles.container}>
        <Title title={{center:"消息"}}></Title>

        <SearchBar
          ref='searchBar'
          placeholder='搜索'
          hideBackground={true}
          onCancelButtonPress={this._onCancelButtonPress.bind(this)}
          onSearchButtonPress={this._onSearchButtonPress.bind(this)}
          onChangeText={this._onChangeText.bind(this)}
          onFocus={() => this.setState({showsCancelButton: true})}
          showsCancelButton={this.state.showsCancelButton}
        />

        <ListView dataSource={this.state.dataSource}
          renderSeparator={this._renderSeparator.bind(this)}
          renderRow={this._renderRecord.bind(this)}
          renderSectionHeader={this._renderSectionHeader.bind(this)}
          enableEmptySections={true}
          style={styles.listView} />

       </View> 
    )

  }
}

//定义本模块的样式表
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#eeeeee',
    flex: 1,
  },
  listView: {
  },
  listRow:{
    flexDirection:'row',
    alignSelf:'stretch',
    flex: 1,
    height:55,
    backgroundColor: 'white',
    padding: 20,
    alignItems:'center',
  },
  separatorView:{
    height:1,
    backgroundColor:'#eee',
  },
  sectionHeader:{
    height:28,
    justifyContent:'center',
    backgroundColor:'#ddd',
  },
  setionHeaderText:{
    marginLeft:40,
    fontSize:14,
    color:'#aaa',
  },
  contactor:{
    fontSize:14,
    textAlign:'center',
    marginLeft:5,
  },
  location:{
    flexDirection:'row',
    marginLeft:30,
    alignSelf:'flex-end',
  },
  school:{
    fontSize:10,
    color:'gray',
  },
  avatar: {
    borderRadius:20,
    width: 40,
    height: 40
  }
})

module.exports = ChatList;